#!/usr/bin/python
# -*- coding:utf-8 -*-
#scriptName:publisher.py

##  date : 2013 / 10 / 09
##  publisher_edited.py was modified by wqg
"""
command line:
import OF3D_TDCmd.publishingFirm.publisher as rigPubLis
reload(rigPubLis)
RigPubLisCls = rigPubLis.PublishRigFile()

updata notes:
at version:
1.0.1:
        beta version
1.0.2:
        separate function to method.
1.0.3: add method
        lockThisObjsVis
1.0.4:
        mesh type set move on self.vis
1.0.5:
        at Unlock Normals set soften Edge
1.0.6:
    refMeshShape
        #ignore intermediateObject object
1.0.7: 121019
    add new checks:
        Check Instance Copy
        Close All Window
        Subd Mesh To 1
        Four View
        Mesh Wireframe Display
        OFF Wireframe on Shaded
        Fit Objects In Panel
    new button:
        Check Scene Name
"""
#__version__ = '1.0.7 121019'
__version__ = '1.0.8 101013'
import maya.cmds as mc
import maya.mel as mel
import maya.OpenMaya as om
import re,os
import OF3D_zchExportSkinClusterWeight as WeightPy
import OF3D_zchPipePublicClass as PublicClass

import OF3D_rigToolkits as tks
import OF3D_zOpsMeshOrig as meshManage
reload(PublicClass)

from OF3D_PublicClass import qualityAssurance
reload(qualityAssurance)

import gg_tool
reload(gg_tool)
import updateVisWin
reload(updateVisWin)
import lockTransformOfChannel
reload(lockTransformOfChannel)

#import publisher as publish
#Pub = publish.PublishRigFile()


class PublishRigFile(qualityAssurance.QualityAssurance,tks.Toolkits,PublicClass.PublicClass,WeightPy.SkinWeightImExport,meshManage.ShapeOrigOprate,gg_tool.gg_tool,updateVisWin.updateWin,lockTransformOfChannel.LockTransformOfChannel):
        "make scence clean"
        def __init__(self):
                qualityAssurance.QualityAssurance.__init__(self)
                PublicClass.PublicClass.__init__(self)
                self.set_ctrl='set_ctrl'
                #maybe used object name
                self.headGeo = "head_geo"
                self.modify = "modify"
                self.vis = "visibility_ctrl"     #be modified >"Visibility"
                self.of3dRig = "of3d_rig"
                self.faciGrp = "facial_grp"
                self.faciPal = "FacialPanel_grp"
                self.allCtrls = "Allctrls"
                if mc.objExists('set_ctrl'):
                        self.allCtrlSets  = mc.sets('set_ctrl',q=1)
                #ui about
                self.pubRigWinRootLayout = "of_publishRigToll_rootlayout"
                self.baseOpvName = "ribPb_uiOpv_"

                self.publishRigVersion = __version__
                if self.mayaVersion=="2011":
                        skMll = "skinConform2011x64.mll"
                        try:
                                if mc.pluginInfo(skMll,q=True,loaded=True)==0:
                                        mc.loadPlugin(skMll)
                                if mc.pluginInfo(skMll,q=True,autoload=True)==0:
                                        mc.pluginInfo(skMll,e=True,autoload=True)
                        except Exception,e:
                                print "Warning: %s"%(e)
        def lockHideLocShape(self,ptType=True):
                'lock and hide all locator shape'
                allLocator = mc.ls(type="locator")
                for x in allLocator:
                        mc.setAttr("%s.visibility"%(x),lock=False)
                        mc.setAttr("%s.visibility"%(x),0)
                        mc.setAttr("%s.visibility"%(x),lock=True)
                self.mayaPrint("Hide all locator shape.",ptType)
                return True
                
        def importAllRefs(self,ptType=True):
                'import file form refs'
                refs = mc.ls(references=1)
                for x in refs:
                        try:
                                filePath = mc.referenceQuery(x,filename=True )
                                mc.file(filePath,importReference=1)
                        except:
                                pass
                        if mc.objExists(x):
                                mc.lockNode(x,lock=False)
                                mc.delete(x)
                                self.mayaPrint( "delete %s;"%( x ),addResult=False )
                self.mayaPrint("Import all of reference.",ptType)
                return True
        def delSpilthDislayer(self,ptType=True):
                'delete spilth display layer and set the order'
                allDisLayer = mc.ls(type="displayLayer")
                for x in allDisLayer:
                        if re.search("ctrl$|^defaultLayer$",x)==None:
                                mc.delete(x)
                        #model$|
                        #if re.search("model$",x)!=None:
                        #        mc.setAttr("%s.visibility"%(x),1)
                        #        mc.setAttr("%s.displayType"%(x),2)
                        #        mc.setAttr("%s.displayOrder"%(x),1)
                        if re.search("ctrl$",x)!=None:
                                mc.setAttr("%s.visibility"%(x),1)
                                mc.setAttr("%s.displayType"%(x),0)
                                mc.setAttr("%s.displayOrder"%(x),1)
                self.mayaPrint("Delete spilth display layer and set the order.",ptType)
                return True
        def delNeedDelete(self,ptType=True):
                'delete BodyNeedDelete BodyNeedDelete_grp HeadNeedDelete HeadNeedDelete_grp'
                needDeleteList = ["BodyNeedDelete","BodyNeedDelete_grp","HeadNeedDelete","HeadNeedDelete_grp","needDelete"]
                for x in needDeleteList:
                        if mc.objExists(x):
                                mc.delete(x)
                self.mayaPrint("Delete %s."%(needDeleteList),ptType)
                return True
        def pb_delNotDrivenKey(self,ptType=True):
                'delete all keyframe and it is not driven key'
                self.deleteNotDrivenKey(deleteLocked=False)
                self.mayaPrint("Delete keyframes.",ptType)
                return True

        def resetAllCtrls(self,ptType=True):
                'reset sets of %s'%(self.allCtrls)
                if mc.objExists(self.allCtrls):
                        mc.select(self.allCtrls)
                        self.resetSelCTL()
                self.mayaPrint("Reset all ctrls.",ptType)
                return True

        def lockHideLoc_and_IKHa(self,ptType=True):
                'lock and hide all locator shape and ikHandle'
                allLocator = mc.ls(type="locator")
                all_ikhandle = mc.ls(type="ikHandle")
                for x in all_ikhandle:
                        mc.setAttr("%s.visibility"%(x),lock=False)
                        mc.setAttr("%s.visibility"%(x),0)
                        mc.setAttr("%s.visibility"%(x),lock=True)

                for x in allLocator:
                        mc.setAttr("%s.visibility"%(x),lock=False)
                        mc.setAttr("%s.visibility"%(x),0)
                        mc.setAttr("%s.visibility"%(x),lock=True)
                self.mayaPrint("Hide all locator shape.",ptType)
                self.lock_SN_HP()
                return True
        def lock_SN_HP(self):
                #All goemetries are mended undoubleSided
                SN = mc.ls('*_SN*',type='transform')
                PH = mc.ls('*_PH*',type='transform')

                for i in SN:
                        mc.setAttr('%s.sx'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.sy'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.sz'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.v'%(i),l=1,k=0,cb=0)

                for i in PH:
                        mc.setAttr('%s.sx'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.sy'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.sz'%(i),l=1,k=0,cb=0)
                        mc.setAttr('%s.v'%(i),l=1,k=0,cb=0)

        def lockChannelNotCtrl(self,ptType=True):
                '''
                scriptPath = __name__
                importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)

                ls_Type = "%s.lsType('of3d_rig','transform',1)"%(importStr)
                "lock transform channel of not _ctrl"
                lockList = ["*_zero","*_Zero"]
                for x in lockList:
                        allNeedLock = mc.ls(x,type="transform")
                        for tfm in allNeedLock:
                                for atr in ['tx','ty','tz','rx','ry','rz','sx','sy','sz','v']:
                                        mc.setAttr("%s.%s"%(tfm,atr),lock=True)
                                        mc.setAttr("%s.%s"%(tfm,atr),0)
                                        #print "setAttr -lock 1 %s.%s;"%(tfm,atr)
                self.mayaPrint("lock %s channel."%(lockList),ptType)
                return True
                '''
                "lock transform channel of not _ctrl"
                lockList = ["*_zero","*_Zero","*_loc","*_grp","*_sdk","*_con","*_end"]
                for x in lockList:
                        allNeedLock = mc.ls(x,type="transform")
                        for tfm in allNeedLock:
                                for atr in ['tx','ty','tz','rx','ry','rz','sx','sy','sz','v']:
                                        mc.setAttr("%s.%s"%(tfm,atr),lock=True)
                                        mc.setAttr("%s.%s"%(tfm,atr),0)
                                        #print "setAttr -lock 1 %s.%s;"%(tfm,atr)
                self.mayaPrint("lock %s channel."%(lockList),ptType)
                return True

        def lockJointOrient(self,ptType=True):
                'lock all joints.jointOrient'
                allJoints = mc.ls(type="joint")
                for jnt in allJoints:
                        mc.setAttr("%s.jointOrient"%(jnt),lock=True)
                self.mayaPrint("lock jointOrient of all joints.",ptType)
                return True
        def unLockMeshNormals(self,ptType=True):
                "set all meshs Unlock Normals and soften Edge //"
                allMeshs = mc.ls(type="mesh")
                for mesh in allMeshs:
                        mc.polyNormalPerVertex( mesh, ufn=True )
                        polyNormalNodes = mc.ls( mc.listHistory(mesh), type="polyNormalPerVertex" )
                        for nod in polyNormalNodes:
                                mc.delete(nod)
                for mesh in allMeshs:
                        if mc.objExists( mesh ):
                                imdObj = mc.getAttr( "%s.intermediateObject"%(mesh) )
                                if imdObj==True:
                                        continue
                                itsParent = mc.listRelatives(mesh,p=1,f=1)
                                mc.select(itsParent)
                                self.softEdgeShapeOrig(printResult=False)
                        else:
                            #may be delete mesh at delete -ch time
                            print "Check it %s"%( mesh )
                self.mayaPrint("set all meshs Unlock Normals and soften Edge //",ptType)
                return True
        def refSkindCurve(self,ptType=True):
                'hide has skin nurbs curve'
                allCurves = mc.ls(type="nurbsCurve")
                for x in allCurves:
                        if mc.ls(mc.listHistory(x),type="skinCluster")!=[]:
                                mc.setAttr("%s.overrideEnabled"%(x),1)
                                mc.setAttr("%s.overrideDisplayType"%(x),2)
                self.mayaPrint("Set curve(is skined) display type-Reference.",ptType)
                return True
        def refMeshShape(self,ptType=True):
                scriptPath = __name__
                importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)
                "%s.LOHI_Trans()"%(importStr)
                'set all mesh shape display type Reference'

                meshDT = "%s.meshDisplayType"%(self.vis)
                if not mc.objExists(self.vis):
                    self.mayaWarning("No object %s."%(self.vis),ptType)
                    return
                if mc.objExists(meshDT)==False:
                        mc.addAttr(self.vis,ln="meshDisplayType", at="enum",en="Normal:Template:Reference:",keyable=True)
                        mc.setAttr(meshDT,keyable=False,channelBox=True)

                Meshs = mc.ls(type="mesh")
                nurbsSurfaces = mc.ls(type="nurbsSurface")

                allMeshs=Meshs+nurbsSurfaces
                for x in allMeshs:
                        #ignore intermediateObject object
                        imdObj = mc.getAttr( "%s.intermediateObject"%(x) )
                        if imdObj==True:
                                continue
                        #set overrideEnabled
                        mc.setAttr("%s.overrideEnabled"%(x),lock=False)
                        mc.setAttr("%s.overrideEnabled"%(x),1)
                        mc.setAttr("%s.overrideEnabled"%(x),lock=True)
                        #set overrideDisplayType
                        mdt = "%s.overrideDisplayType"%(x)
                        isLock = mc.getAttr(mdt,lock=True)
                        if mc.isConnected(meshDT,mdt)==False and isLock==False:
                                mc.connectAttr(meshDT,mdt,f=True)
                mc.setAttr(meshDT,2)
                self.mayaPrint("Set scene mesh display type-Reference.",ptType)
                return True
        def delAllBindPose(self,ptType=True):
                'delete all bindPose'
                allBindPos = mc.ls(type = "dagPose")
                for x in allBindPos:
                        mc.lockNode(x,lock=False)
                        mc.delete(x)
                self.mayaPrint("Delete all bindPose.",ptType)
                return True
        def delPluginNode(self,ptType=True):
            "delete plugin node"
            corrective2008,corrective2011 = [],[]

            try:
                corrective2008 = mc.ls(type="correctiveShape")
            except:
                pass
            for x in corrective2008:
                out = mc.listConnections("%s.outputGeometry"%(x),d=True,s=False,scn=True)
                if out!=None:
                    mc.delete(out[0],ch=True)
            #self.mayaPrint("Delete all correctiveShape node 2008.",ptType)
            try:
                corrective2011 = mc.ls(type="sculptToBlendTarget")
            except:
                pass
            for x in corrective2011:
                out = mc.listConnections("%s.outMesh"%(x),d=True,s=False,scn=True)
                if out!=None:
                    mc.delete(out[0],ch=True)
            self.mayaPrint("Delete all correctiveShape nodes 2008 and higher.",ptType)
            return True
        def removeSkinClusterUnusedInfluence(self,ptType=True):
                'remove all skinCluster Unused Influence'
                allSkinNode = mc.ls(type="skinCluster")
                for x in allSkinNode:
                        self.removeUnusedInfluence(x,ptType)
                self.mayaPrint("Remove SkinCluster Unused Influence",ptType)
                return True
        def setLambert1NoConnectIn(self,ptType=True):
                'set Lambert1 no connect in'
                if mc.objExists("lambert1.color"):
                        for atr in ["color","transparency"]:
                                conInNode = mc.listConnections("lambert1.%s"%(atr),d=False,s=True,p=True)
                                if conInNode!=None:
                                        mc.disconnectAttr(conInNode[0],"lambert1.%s"%(atr))
                                        self.mayaPrint("disconnectAttr %s lambert1.%s;"%(conInNode[0],atr),ptType)
                                else:
                                        self.mayaPrint("lambert1.%s No connect in."%(atr),ptType)
                return True
        def breakMaterialsConnect(self,ptType=True):
            allMates = mc.ls(materials=True)
            atributeList = ["transparency","normalCamera","incandescence","ambientColor"]
            #default shader "lambert1","particleCloud1","shaderGlow1"
            for shd in allMates:
                for atr in atributeList:
                    shaderAtr = "%s.%s"%(shd,atr)
                    if mc.objExists( shaderAtr ):
                        conInNode = mc.listConnections( shaderAtr,d=False,s=True,p=True)
                        if conInNode!=None:
                            mc.disconnectAttr(conInNode[0],shaderAtr )
            self.mayaPrint("disconnectAttr Materialss.%s;"%( atributeList ),ptType)
            return True
        def deleteUnusedNodes(self,ptType=True):
                'deleteUnusedNodes'
                try:
                        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
                except:
                        pass
                self.mayaPrint("Delete Unused Nodes.",ptType)
                return True
        def lockThisObjsVis(self,lkit=True,ptType=True):
                #needLockList = ["transform","mesh","nurbsCurve"]
                needLockList = ["transform","mesh"]
                "lock unlock vis type is %s"%(needLockList)
                objs = mc.ls(type=needLockList)
                for o in objs:
                        mc.setAttr("%s.v"%(o),lock=lkit)
                self.mayaPrint("set %s.vis lock=%s."%(needLockList,lkit),ptType)
                return True
        def objLinkASet(self):
            allCtrls = mc.ls("*_ctrl",type="transform")
            #allCtrls = ["pSphere1_ctrlShape"]
            rootRes = True
            for obj in allCtrls :
                objMObj = self.getMObjByName( obj )
                objDeNode = om.MFnDependencyNode( objMObj )
                plug = objDeNode.findPlug( "instObjGroups" )
                elem = plug.elementByLogicalIndex(0)
                connectTo = om.MPlugArray()
                elem.connectedTo(connectTo,0,1)
                conectASet = False
                for idx in range( connectTo.length() ):
                    tarMObj = connectTo[idx].node()
                    if tarMObj.apiType()==om.MFn.kSet:
                        conectASet=True
                        break
                #connect to deNode no one sets
                if conectASet==False:
                    selectCmd = "from maya import cmds\ncmds.select('%s')"%( obj )
                    self.mayaWarning("This Ctrl not in a set <%s>"%(obj),True,command=selectCmd )
                    rootRes = False
            if rootRes == True:
                self.mayaPrint("Check Ctrl link a set successfull",True)
            return rootRes
        def userMelCommand(self,ptType=True):
                'running usercommand.mel'
                location = mc.file(q=True,loc=True)
                sperate = re.split("/",location)
                skipLastStr = re.sub(sperate[-1],"",location)
                userCommandMel = "%susercommand.mel"%(skipLastStr)
                cmdColor = [1,1,0]
                if os.path.exists(userCommandMel)==False:
                        f = file(userCommandMel,"w")
                        f.close()
                if os.path.exists(userCommandMel):
                        mel.eval('source "%s";'%(userCommandMel))
                        self.mayaPrint("Running usercommand:",True,cmdColor,False)
                        f = file(userCommandMel,"r")
                        for line in f:
                                skipSpace = re.sub(r"\r|\n","",line)
                                self.mayaPrint(skipSpace,True,cmdColor,False)
                        f.close()
                return True
        def addOFNameSpace(self,whichGrp,nameSpace,onlyDnObjs):
                """
                """
                if mc.namespace(ex=nameSpace)==False:
                        mc.namespace(add=nameSpace)
                if onlyDnObjs==True:
                        allObjs = self.getAllChildren(whichGrp,"transform")
                else:
                        allObjs = self.getAllObjs(whichGrp,"transform")
                #allObjs = self.getAllChildren(self.of3dRig,"transform")
                if mc.objExists("Allctrls"):
                        allObjs.append("Allctrls")
                for x in allObjs:
                        try:
                                mc.rename(x,"%s:%s"%(nameSpace,self.getLastName(x)))
                        except:
                                print x
                self.mayaPrint("Add nameSpace [OF] for every transform.",ptType)
                return True
        def checkSceneName(self):
            cmpt = mc.optionMenuGrp("rigPb_Components_omg",q=True,v=True)
            subdSl = mc.radioButtonGrp("rigPbComponents_LH_rbt",q=True,sl=True)
            if subdSl==1:
                subd = "LO"  #< "LW" be modified "LO"
            else:
                subd = "HI"
            fmtSl = mc.radioButtonGrp("rigPbComponents_ft_rbt",q=True,sl=True)
            if fmtSl==1:
                fmt="ma"
            else:
                fmt="mb"
            self.qa_ckFileName(cmpt,subd,fmt,1)

        def remberCheckBoxSelect(self):

            baseOpvName=self.baseOpvName
            idx = 1
            allChild = mc.layout(self.pubRigWinRootLayout,q=1,childArray=1)
            for c in allChild:
                try:
                    #to know is checkBoxGrp?
                    val = mc.checkBoxGrp(c,q=True,v1=True)
                    opv = mc.optionVar( q = "%s%s"%(baseOpvName,idx) )
                    if val!=opv:
                        mc.optionVar( iv = ("%s%s"%(baseOpvName,idx),val) )
                        print " remberCheckBoxSelect ",c
                    #next option var
                    idx += 1
                except:# Exception,e:
                    pass
        def runingSelected(self):

            res = True
            #exec("import %s as publish\nPub = publish.PublishRigFile()"%(__name__) )
            self.mayaPrint("publishRig %s"%(self.publishRigVersion))
            of3dModify = "%s.%s"%(self.of3dRig,self.modify)
            if mc.objExists(of3dModify):
                mc.setAttr(of3dModify,lock=False)
                mc.setAttr(of3dModify,0)

            allChild = mc.layout(self.pubRigWinRootLayout,q=1,childArray=1)
            for c in allChild:
                try:
                    #to know is checkBoxGrp?
                    val = mc.checkBoxGrp(c,q=True,v1=True)
                    ann = mc.checkBoxGrp(c,q=True,ann=True)
                    #get command from checkBoxGrp ann
                    if val==1 and c!="pbRig_userCommand_cbg":
                        exec( "reVal = %s"%(ann) )
                        if reVal!=True and reVal!=[]:
                            res = False
                except:# Exception,e:
                    pass
            #set of3d modify 10 and lock it
            if mc.objExists(of3dModify):
                mc.setAttr(of3dModify,10)
                mc.setAttr(of3dModify,lock=True)
                self.mayaPrint("Set %s=10 and lock it."%(of3dModify),True)
            #currective EyesCtlFol_head EyesCtlFol_lock
            if mc.objExists("EyesCtlFol_head") and mc.objExists("EyesCtlFol_lock"):
                pos = mc.xform("EyesCtlFol_head",q=True,ws=True,t=True)
                mc.xform("Parent_All|EyesCtlFol_lock",ws=True,t=pos)
            cameraName = "Facial_PanelShape"
            if mc.objExists(cameraName):
                mc.setAttr("Facial_PanelShape.orthographic",1)
                mc.setAttr("Facial_PanelShape.orthographic",lock=1)
                self.mayaPrint("setAttr Facial_PanelShape.orthographic 1; and lock",True)

            #user mel command runing last
            val = mc.checkBoxGrp("pbRig_userCommand_cbg",q=True,v1=True)
            if val:
                self.userMelCommand()
            #add nameSpace OF:   for every transform
            #result = self.confirmDialog("Add nameSpace [OF] for every transform.",['Yes','NO'])
            #if result=="Yes":
            #        self.addOFNameSpace(self.of3dRig,"OF",ptType)
            mc.select(cl=1)
            if res==True:
                self.mayaPrint("--WELL DONE--.",True)

        def pr_win(self):
            winName = 'of_publishRigRoom_win'
            self.closeWindow( winName )
            mc.window(winName, title='OF Publish Rig Tool v%s'%(__version__),menuBar=True)
            #self.winMenuBar("pass")
            root = mc.columnLayout(adj=True)
            tabsLyot = mc.tabLayout()
            toosLyot = mc.columnLayout(adj=True)
            self.pr_tools()
            mc.setParent("..")

            checksLyot = mc.columnLayout(self.pubRigWinRootLayout,adj=True)
            self.pr_checks()
            mc.setParent("..")
            mc.tabLayout(tabsLyot,edit=True,sti=2,tabLabel=((toosLyot,"|--------Tools--------|"),(checksLyot,"|--------Checks--------|")) )

            mc.setParent( root )
            mc.separator(st="single")
            mc.text(label="(C)Original Force | ChunHai Zhao 201210161806",en=0)
            mc.separator(st="single")

            mc.showWindow(winName)
        
        def pr_tools(self):
            scriptPath = __name__
            scriptGG =  gg_tool
            importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)
            butIndex = 1
            checkname=mel.eval('source "U://RiggerAdderMenu//RC_scriptsCommands//gg_checkSameName.mel"')
            #mc.button(label=" %s.  Import All References"%(('%d'%(butIndex)).zfill(2)),c="%s.importAllRefs(0)"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s. Check same name"%(("%s"%(butIndex)).zfill(2)),c='mel.eval("gg_checkSameName")',al="left");butIndex+=1
            mc.button(label=" %s.  Set_ctrl check"%(("%s"%(butIndex)).zfill(2)),c= lambda *args:self.ctrlQuery(),al="left");butIndex+=1
            #mc.button(label=" %s. Check shape name"%(("%s"%(butIndex)).zfill(2)),c='',al="left");butIndex+=1
            mc.button(label=" %s.  Lock And Hide locatorShape and ikHandle.v"%(("%s"%(butIndex)).zfill(2)),c="%s.lockHideLoc_and_IKHa(0)"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  Lock Transform Channel Of Not _ctrl"%(("%s"%(butIndex)).zfill(2)),c="%s.transformListWin()"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  Lock Joint Orient"%(("%s"%(butIndex)).zfill(2)),c=lambda *args:self.lockJointOrient(0),al="left");butIndex+=1
            mc.button(label=" %s.  Reset set_ctrl Allctrls"%(("%s"%(butIndex)).zfill(2)),c= lambda *args:self.ctrlResetQuery(),al="left");butIndex+=1
            mc.button(label=" %s.  Link Mesh With %s.meshDisplayType "%(("%s"%(butIndex)).zfill(2),self.vis),c= lambda *args:self.refMeshShape(0) ,al="left");butIndex+=1
            mc.button(label=" %s.  Unlock Normals Mesh"%(("%s"%(butIndex)).zfill(2)),c=lambda *args:self.unLockMeshNormals(0) ,al="left");butIndex+=1
            mc.button(label=" %s.  Remove SkinCluster UnusedInfluence6"%(("%s"%(butIndex)).zfill(2)),c=lambda *args:self.removeSkinClusterUnusedInfluence(0),al="left");butIndex+=1
            mc.button(label=" %s.  Delete Unused Nodes"%(("%s"%(butIndex)).zfill(2)),c= lambda *args:self.deleteUnusedNodes(0) ,al="left");butIndex+=1
            mc.button(label=" %s.  Delete Splith Display Layer"%(("%s"%(butIndex)).zfill(2)),c= lambda *args:self.delSpilthDislayer(0) ,al="left");butIndex+=1
            mc.button(label=" %s.  Delete Not Driven Keys"%(("%s"%(butIndex)).zfill(2)),c=lambda *args:self.pb_delNotDrivenKey(0),al="left");butIndex+=1
            mc.button(label=" %s.  Delete BindPose10"%(("%s"%(butIndex)).zfill(2)),c="%s.delAllBindPose(0)"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  Joint Hide setting oper"%(("%s"%(butIndex)).zfill(2)),al="left",c= '%s.hideJoint()'%(importStr));butIndex+=1
            mc.button(label=" %s.  UpdateVis"%(("%s"%(butIndex)).zfill(2)),al="left",c='%s.importInfo()'%(importStr));butIndex+=1
            mc.button(label=" %s.  Edit goe (HI,LO) sidedness [the commend is used for characters]"%(("%s"%(butIndex)).zfill(2)),c= '%s.goemetries_edit()'%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  _EX check and edit deformMesh"%(("%s"%(butIndex)).zfill(2)),al="left",c='%s.check_EX()'%(importStr));butIndex+=1
            mc.button(label=" %s.  Add rotate order"%(("%s"%(butIndex)).zfill(2)),al="left",c= '%s.ctrl_rOrderQuery()'%(importStr));butIndex+=1
            mc.button(label=" %s.  rnkRigUtil"%(("%s"%(butIndex)).zfill(2)),al="left",c='%s.rnkRigUtil()'%(importStr));butIndex+=1

            ##mc.button(label=" %s.  Hide positionA and positionB"%(("%s"%(butIndex)).zfill(2)),al="left",c ="%s.hidePosition_A_B(0)"%(importStr));butIndex+=1
            #mc.button(label=" %s.  Connect %s.FacialPanel to FacialPanel.v"%(("%s"%(butIndex)).zfill(2),self.vis),c="%s.connectVis2FacialPanel(0)"%(importStr),al="left");butIndex+=1
            #mc.button(label=" %s.  Lock Objects Vis"%(("%s"%(butIndex)).zfill(2)),c="%s.lockThisObjsVis(1,0)"%(importStr),al="left");butIndex+=1
            #mc.button(label=" %s.  Set Skined Curve Refs"%(("%s"%(butIndex)).zfill(2)),c="%s.refSkindCurve(0)"%(importStr),al="left");butIndex+=1
            #mc.button(label=" %s.  Unlock Mesh Normals"%(("%s"%(butIndex)).zfill(2)),c="%s.unLockMeshNormals(0)"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  Delete NeedDelete"%(("%s"%(butIndex)).zfill(2)),c="%s.delNeedDelete(0)"%(importStr),al="left");butIndex+=1
            mc.button(label=" %s.  Delete CorrectiveShape Node"%(("%s"%(butIndex)).zfill(2)),c="%s.delPluginNode(0)"%(importStr),al="left");butIndex+=1
            #mc.button(label=" %s.  Run userMelCommand"%(("%s"%(butIndex)).zfill(2)),c="%s.userMelCommand(0)"%(importStr),al="left");butIndex+=1

        def pr_checks(self):
            #init optionVar
            baseOpvName=self.baseOpvName
            for i in range(1,22):
                opv = "%s%s"%(baseOpvName,i)
                if not mc.optionVar( exists = opv ):
                    mc.optionVar(iv=(opv,1))

            scriptPath = __name__
            importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)
            changeComand1 = "%s.remberCheckBoxSelect()"%(importStr)
            rootLayoutName = self.pubRigWinRootLayout
            version = __version__
            butIndex = 1
            importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)
            mc.textFieldGrp(label="Login User:",text=self.userName,ed=0)
            mc.frameLayout( label='Scene Name Option', borderStyle='etchedIn' ,cll=True ,cl=1)
            mc.columnLayout(adj=True)
            mc.separator(style="single")
            Components = mc.optionMenuGrp("rigPb_Components_omg",label='Components:',cl2=["right","center"])
            mc.menuItem( label='MDL' )
            mc.menuItem( label='PRX' )
            mc.menuItem( label='RIG' )
            mc.menuItem( label='TEX' )
            mc.menuItem( label='chrFX' )
            mc.menuItem( label='FLO_chr' )
            mc.radioButtonGrp("rigPbComponents_LH_rbt",label="LW/HI:",la2=["LW","HI"],numberOfRadioButtons=2,sl=2)
            mc.radioButtonGrp("rigPbComponents_ft_rbt",label="Format:",la2=["ma","mb"],numberOfRadioButtons=2,sl=1,en=0)
            mc.setParent("..");mc.setParent("..")
            mc.button(label="Check Scene Name",c="%s.checkSceneName()"%(importStr) )

            #rember user selected
            slVal = self.uiReadAndSetOptionVar(q=True,buttonType="optionMenuGrp",buttonName="rigPb_Components_omg",default=1)
            mc.optionMenuGrp("rigPb_Components_omg",e=True,sl=slVal,cc=(importStr+'.uiReadAndSetOptionVar(e=True,buttonType="optionMenuGrp",buttonName="rigPb_Components_omg")') )
            #rember user selected
            mc.radioButtonGrp("rigPbComponents_LH_rbt",e=True,sl=self.uiReadAndSetOptionVar(q=True,buttonName="rigPbComponents_LH_rbt",default=2),cc=(importStr+'.uiReadAndSetOptionVar(e=True,buttonType="radioButtonGrp",buttonName="rigPbComponents_LH_rbt")') )

            mc.separator(style="single");v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Import All References"%(('%d'%(butIndex)).zfill(2)),ann="self.importAllRefs(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            #mc.checkBoxGrp(label1=" %s.  Import head_geo weight"%(("%s"%(butIndex)).zfill(2)),ann="self.importHeadGeow(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            #mc.checkBoxGrp(label1=" %s.  Connect %s.FacialPanel to FacialPanel.v"%(("%s"%(butIndex)).zfill(2),self.vis),ann="self.connectVis2FacialPanel(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp(label1=" %s.  Check Instance Copy"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_ckInstanceCopy(True)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Close All Window"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_doClearWindow()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Subd Mesh To 1"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_subdMeshto1()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Four View"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_setFourView()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Mesh Wireframe Display"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_wireframeDisplay()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  OFF Wireframe on Shaded"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_wireframeOnShaded()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Fit Objects In Panel"%(("%s"%(butIndex)).zfill(2)),ann="self.qa_fitAllView()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            #mc.checkBoxGrp(label1=" %s.  Check ?_Ctrl link a Sets"%(("%s"%(butIndex)).zfill(2)),ann="self.objLinkASet()",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp(label1=" %s.  Lock And Hide locatorShape.v"%(("%s"%(butIndex)).zfill(2)),ann="self.lockHideLocShape(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Lock Transform Channel Of Not _ctrl"%(("%s"%(butIndex)).zfill(2)),ann="self.lockChannelNotCtrl(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Lock Joint Orient"%(("%s"%(butIndex)).zfill(2)),ann="self.lockJointOrient(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Lock Objects Vis"%(("%s"%(butIndex)).zfill(2)),ann="self.lockThisObjsVis(1,1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp(label1=" %s.  Reset Sets Allctrls"%(("%s"%(butIndex)).zfill(2)),ann="self.resetAllCtrls(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Set Skined Curve Refs"%(("%s"%(butIndex)).zfill(2)),ann="self.refSkindCurve(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Unlock Mesh Normals"%(("%s"%(butIndex)).zfill(2)),ann="self.unLockMeshNormals(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Link Mesh With %s.meshDisplayType"%(("%s"%(butIndex)).zfill(2),self.vis),ann="self.refMeshShape(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Remove SkinCluster UnusedInfluence"%(("%s"%(butIndex)).zfill(2)),ann="self.removeSkinClusterUnusedInfluence(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp(label1=" %s.  Cleanup lambert1"%(("%s"%(butIndex)).zfill(2)),ann="self.setLambert1NoConnectIn(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Cleanup Other Materials"%(("%s"%(butIndex)).zfill(2)),ann="self.breakMaterialsConnect(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp(label1=" %s.  Delete NeedDelete"%(("%s"%(butIndex)).zfill(2)),ann="self.delNeedDelete(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Delete Splith Display Layer"%(("%s"%(butIndex)).zfill(2)),ann="self.delSpilthDislayer(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Delete CorrectiveShape Node"%(("%s"%(butIndex)).zfill(2)),ann="self.delPluginNode(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Delete Not Driven Keys"%(("%s"%(butIndex)).zfill(2)),ann="self.pb_delNotDrivenKey(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Delete BindPose"%(("%s"%(butIndex)).zfill(2)),ann="self.delAllBindPose(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.checkBoxGrp(label1=" %s.  Delete Unused Nodes"%(("%s"%(butIndex)).zfill(2)),ann="self.deleteUnusedNodes(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1;v = mc.optionVar( q="%s%s"%(baseOpvName,butIndex) )
            mc.separator(style="single")
            mc.checkBoxGrp("pbRig_userCommand_cbg",label1=" %s.  Run userMelCommand"%(("%s"%(butIndex)).zfill(2)),ann="self.userMelCommand(1)",cl2=["left","left"],adj=1,v1=v,cc1=changeComand1);butIndex+=1
            mc.separator(style="single")
            mc.button(label="Runing Selected",h=35,bgc=[1,1,0],c="%s.runingSelected()"%(importStr) )
            mc.separator(style="single")
            mc.text(label="(C) Original Force-TD | ChunHai Zhao 121019",en=0)
            mc.separator(style="single")
#when OF Publish Rig Tool remove all down this line
        def pulishroom(self):
            scriptPath = __name__
            importStr = "import %s as publish\nPub = publish.PublishRigFile()\nPub"%(scriptPath)
            winName = 'of_publishRigRoom_win'
            if mc.window(winName, exists=True):
                mc.deleteUI(winName, window=True)
            version = __version__
            butIndex = 1
            mc.window(winName, title='OF-Pulishroom %s-'%(version))
            mc.columnLayout(adj=1)
            self.pr_tools()
            mc.showWindow(winName)

        def pulishroomWin(self):
            #init optionVar
            winName = 'of_publishRigTool_win'
            rootLayoutName = self.pubRigWinRootLayout
            if mc.window(winName, exists=True):
                mc.deleteUI(winName, window=True)
            mc.window(winName,t="OF-RigPublishTool v%s"%(__version__),menuBar=True)
            self.winMenuBar("pass","PublishRigTool.mht")
            mc.columnLayout(rootLayoutName,adj=1)
            self.pr_checks()
            mc.showWindow( winName )
PublishRigFileCls = PublishRigFile()